package org.wxd.sign.aop;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import org.wxd.sign.annotation.SignApi;
import org.wxd.sign.utils.SignUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Objects;


@Slf4j
@ControllerAdvice
public class RequestBodySign implements RequestBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return Objects.nonNull(methodParameter.getMethod()) &&
                SignUtils.isSignInput(methodParameter.getMethod().getAnnotation(SignApi.class));
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {

        SignHttpInputMessage signHttpInputMessage = new SignHttpInputMessage(httpInputMessage,methodParameter);
        if (signHttpInputMessage.isSignError())
            throw new RuntimeException("越权");
        return signHttpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }

    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return o;
    }
}
